package com.hydl.power.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.hydl.power.mapper.*;
import com.hydl.power.pojo.*;
import com.hydl.power.service.SendOrdersService;
import com.hydl.power.service.TemperatureDeviceService;
import com.hydl.power.utils.IdUtil;
import com.hydl.power.utils.PushUtils;
import com.hydl.power.utils.SmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TemperatureDeviceServiceImpl implements TemperatureDeviceService {

    @Autowired
    private TemperatureDeviceMapper temperatureDeviceMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TemperatureDataMapper temperatureDataMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private MarketingMapper marketingMapper;

    @Autowired
    private PushMapper pushMapper;

    @Autowired
    private SendOrdersService sendOrdersService;

    @Autowired
    private GatewayMapper gatewayMapper;

    @Autowired
    private OrderDeliveryMapper orderDeliveryMapper;

    @Override
    public int addTemperatureDevice(String deviceName,String areaId,String areaName,String projectId,String projectName,String powerRoomId,String powerRoomName,String deviceAddress,String serialNumber, String gatewaySn,String deviceMessageAddress) {
        TemperatureDevice temperatureDeviceByTemperatureDeviceName = temperatureDeviceMapper.getTemperatureDeviceByTemperatureDeviceName(deviceName);
        if (temperatureDeviceByTemperatureDeviceName==null){
            Project project = projectMapper.queryProjectByProId(projectId);
            TemperatureDevice temperatureDevice=new TemperatureDevice();
            temperatureDevice.setDeviceId(IdUtil.getRandomString(8));
            temperatureDevice.setDeviceName(deviceName);
            temperatureDevice.setAreaId(areaId);
            temperatureDevice.setAreaName(areaName);
            temperatureDevice.setProjectId(projectId);
            temperatureDevice.setProjectName(projectName);
            temperatureDevice.setPowerRoomId(powerRoomId);
            temperatureDevice.setPowerRoomName(powerRoomName);
            temperatureDevice.setCreateTime(new Date());
            temperatureDevice.setDeviceAddress(deviceAddress);
            temperatureDevice.setSerialNumber(serialNumber);
            temperatureDevice.setGatewaySn(gatewaySn);
            temperatureDevice.setDeviceMessageAddress(deviceMessageAddress);
            temperatureDevice.setTableName(project.getTemperatureDataTableName());
            return temperatureDeviceMapper.addTemperatureDevice(temperatureDevice);
        }
        return 0;

    }

    @Override
    public TemperatureDevice getTemperatureDeviceByTemperatureSerialNumber(String serialNumber) {
        return temperatureDeviceMapper.getTemperatureDeviceByTemperatureSerialNumber(serialNumber);
    }

    @Override
    public List<TemperatureDevice> getTemperatureDeviceByRoomId(String roomId) {
        return temperatureDeviceMapper.getTemperatureDeviceByRoomId(roomId);
    }

    @Override
    public PageInfo<TemperatureDevice> getTemperatureDeviceList(Integer pageNum, Integer pageSize, String areaId, String projectId, String powerRoomId, String token) {
        SysUser user = userMapper.getUserByToken(token);
        if (user!=null){
            if (user.getStatus()==2){
                List<TemperatureDevice> temperatureDevices = temperatureDeviceMapper.selectTemperature(pageNum, pageSize, areaId, user.getProjectId().toString(), powerRoomId);
                return new PageInfo<>(temperatureDevices);
            }
        }
        List<TemperatureDevice> list= temperatureDeviceMapper.selectTemperature(pageNum,pageSize,areaId,projectId,powerRoomId);
        return new PageInfo<>(list);
    }


    @Override
    public List<TemperatureData> getTemperatureDataList(String powerRoomId) {
        List<TemperatureDevice>  temperatureDeviceList=temperatureDeviceMapper.getTemperatureDeviceByRoomId(powerRoomId);
        List<TemperatureData> temperatureDataList=new ArrayList<>();
        if (temperatureDeviceList.size()>0){
            ObjectMapper objectMapper=new ObjectMapper();
            for (TemperatureDevice temperatureDevice:temperatureDeviceList){
                Object object = redisTemplate.opsForValue().get(temperatureDevice.getSerialNumber());
                if (object!=null){
                    TemperatureData temperatureData = objectMapper.convertValue(object, TemperatureData.class);
                    temperatureDataList.add(temperatureData);
                }
            }
        }
        return temperatureDataList;
    }

    @Override
    public List<TemperatureData> getTemperatureDataLine(String deviceId,String time) {
        TemperatureDevice temperatureDeviceByTemperatureSerialNumber = temperatureDeviceMapper.getTemperatureDeviceByTemperatureSerialNumber(deviceId);
        return temperatureDataMapper.getTemperatureDataLine(deviceId, time,temperatureDeviceByTemperatureSerialNumber.getTableName());
    }

    @Override
    public List<TemperatureData> getTemperatureDevicePowerData(String serialNumber,String time) {
        TemperatureDevice temperatureDevice = temperatureDeviceMapper.getTemperatureDeviceByTemperatureSerialNumber(serialNumber);
        if (temperatureDevice!=null){
            if (StringUtils.isNotBlank(temperatureDevice.getTableName())){
                List<TemperatureData>  list = temperatureDataMapper.getPowerDataBySerialNumber(serialNumber,time,temperatureDevice.getTableName());
                return list;
            }
        }
        return null;
    }



  /**
   * 电气火灾断电告警
   */
  @Scheduled(cron = "0/20 * * * * ?")
  public void deviceAlarm() throws Exception {
    List<Gateway> gatewayList = gatewayMapper.getGatewayByBrand(2);
    for (Gateway gateway : gatewayList) {
      List<TemperatureDevice> temperatureDeviceList = temperatureDeviceMapper.getTemperatureDeviceByGatewaySnAlarmStatus(gateway.getGatewayRemark());
      if (temperatureDeviceList.size() > 0) {
        for (TemperatureDevice temperatureDevice : temperatureDeviceList) {
          Object temperaturePowerData = redisTemplate.opsForValue().get(temperatureDevice.getSerialNumber());
          System.out.println(temperaturePowerData);
          if (temperaturePowerData == null) {
            if(temperatureDevice.getCommunicationStatus() != 1){
              temperatureDevice.setAlarm(temperatureDevice.getAlarm()+1);
              temperatureDeviceMapper.updateDeviceAlarmByDeviceId(temperatureDevice.getDeviceId(), temperatureDevice.getAlarm(), 0);
              //if (temperatureDevice.getCommunicationStatus()==1) {
              //if (temperatureDevice.getAlarm() == 1) {
              if(temperatureDevice.getAlarm()==5){
                sendOrdersService.sendOrdersTemperatureDevice(temperatureDevice);
/*                OrderDelivery orderDelivery = new OrderDelivery();
                orderDelivery.setOrderDeliveryId(IdUtil.getRandomString(8));
                orderDelivery.setOrderTypes(1);
                orderDelivery.setRank(1);
                orderDelivery.setFault("电器火灾通讯中断");
                orderDelivery.setFaultTime(new Date());
                orderDelivery.setFaultTypes(4);
                //工单状态  1待派送 2待处理(派送工单) 3处理中 4 忽略工单(以忽略) 5 以结束
                orderDelivery.setOrderStatus(3);
                //是否告警 1 告警 2 不告警
                orderDelivery.setFlag(1);
                orderDelivery.setAreaId(temperatureDevice.getAreaId());
                orderDelivery.setAreaName(temperatureDevice.getAreaName());
                orderDelivery.setProjectId(temperatureDevice.getProjectId());
                orderDelivery.setProjectName(temperatureDevice.getProjectName());
                orderDelivery.setRoomId(temperatureDevice.getPowerRoomId());
                orderDelivery.setRoomName(temperatureDevice.getPowerRoomName());
                orderDelivery.setDeviceId(temperatureDevice.getDeviceId());
                orderDelivery.setDeviceName(temperatureDevice.getDeviceName());
                orderDelivery.setDeviceAddress(temperatureDevice.getDeviceAddress());
                orderDelivery.setSn(temperatureDevice.getSerialNumber());
                //二次查询redis数据是否存在
                // Object temperaturePowerDatas = redisTemplate.opsForValue().get(temperatureDevice.getSerialNumber());
                //if(temperaturePowerDatas==null){
                //三次查询redis数据是否存在
                //Object PowerDatas = redisTemplate.opsForValue().get(temperatureDevice.getSerialNumber());
                //if(PowerDatas== null){
                int insert = orderDeliveryMapper.insert(orderDelivery);
                temperatureDeviceMapper.updateDeviceAlarmByDeviceId(temperatureDevice.getDeviceId(), 0, 1);
                //推送
                List<String> clientIdList = pushMapper.getClientId(orderDelivery.getProjectId());
                PushUtils.sendMessage(clientIdList, orderDelivery.getRoomName(), orderDelivery.getDeviceName(), orderDelivery.getFault());*/


              }
              //}
            }
            //}
            //System.out.println(temperatureDevice.getDeviceName() + "设备通讯中断" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                           /* } else {
                                temperatureDeviceMapper.updateDeviceAlarmByDeviceId(temperatureDevice.getDeviceId(), 1,null);
                            }*/
            // }
          } else {
            //if (temperatureDevice.getCommunicationStatus() != 1  || temperatureDevice.getAlarm()==1) {
            temperatureDeviceMapper.updateDeviceAlarmByDeviceId(temperatureDevice.getDeviceId(), 0, 0);
            //}
          }
        }
      }
    }
  }


    @Override
    public int updateTemperatureDeviceById(Integer id,String deviceName,String deviceAddress,String deviceMessageAddress,String serialNumber) {
        TemperatureDevice temperatureDevice=new TemperatureDevice();
        temperatureDevice.setId(id);
        temperatureDevice.setDeviceName(deviceName);
        temperatureDevice.setDeviceAddress(deviceAddress);
        temperatureDevice.setDeviceMessageAddress(deviceMessageAddress);
        temperatureDevice.setSerialNumber(serialNumber);
        return  temperatureDeviceMapper.updateByPrimaryKeySelective(temperatureDevice);
    }

    @Override
    public int deleteTemperatureDeviceById(Integer id) {
        return temperatureDeviceMapper.deleteByPrimaryKey(id);
    }

    @Override
    public TemperatureDevice getTemperatureDeviceByTemperatureDeviceId(String deviceId) {
        return temperatureDeviceMapper.getTemperatureByTemperatureDeviceId(deviceId);
    }

    @Override
    public List queryDevice(String projectId, String powerRoomId) {
        List<TemperatureDevice> temperatureDevices = temperatureDeviceMapper.queryDevice(projectId, powerRoomId);
        Map map = new HashMap();
        List list = new ArrayList();
        for (TemperatureDevice temperatureDevice : temperatureDevices) {
            map.put("temperatureA","");
            map.put("temperatureB","");
            map.put("temperatureC","");
            map.put("temperatureN","");
            map.put("deviceId",temperatureDevice.getSerialNumber());
            map.put("deviceName",temperatureDevice.getDeviceName());
            map.put("electricLeakage","");
            list.add(map);
            map=new HashMap();
        }
        return list;
    }
}
